package oa.shiro;

import javax.annotation.Resource;

import oa.bean.TUser;
import oa.service.UserService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Lazy;

//@Component
public class RedisRealm extends AuthorizingRealm {
	@Resource
	@Lazy
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("权限配置-->RedisRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String username = principals.getPrimaryPrincipal().toString();
        TUser user = userService.login(username);
        authorizationInfo.addRole(user.getOskey());
        authorizationInfo.addStringPermissions(userService.getQxcd(username));
        return authorizationInfo;
    }
 
    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        System.out.println("验证配置-->RedisRealm.doGetAuthenticationInfo()");
        //获取用户的输入的账号.
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        //通过username从数据库中查找 User对象，如果找到，没找到.
        TUser user = userService.login(upToken.getUsername());
        if (user == null) {
            throw new AuthenticationException("您输入的用户名不存在");
        } else if(user.getJinyong() == 1) {
        	throw new AuthenticationException("该用户名已被禁止登录");
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getUsername(), //用户
                user.getUserpassword(), //密码
                //ByteSource.Util.bytes(username),salt=username+salt
                getName()  //realm name
        );
        return authenticationInfo;
    }
    /**
     * 清理缓存权限
     */
    public void clearCachedAuthorizationInfo()
    {
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

}
